package com.gis3c.sys.web.controller;

import com.gis3c.sys.service.RoleService;
import com.gis3c.sys.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * Created by hukekuan on 2017/9/23.
 */
@Controller
public class MainController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    /**
     * 后台管理首页
     * @return
     */
    @RequestMapping(value = "/admin")
    public String Index(){
        Subject subject = SecurityUtils.getSubject();
        String userName = subject.getPrincipal().toString();
        Set<String> roleIds = roleService.findRolesByUserName(userName);

        System.out.println("==========================");
        System.out.println(subject.hasRole("admin"));
        System.out.println("==========================");

        return "index";
    }
    @RequestMapping(value = "/href=")
    public void Index1(HttpServletResponse response) throws IOException {
        response.sendRedirect(".");
    }

    /**
     * Form登录页面
      * @param req
     * @param model
     * @return
     */
    @RequestMapping(value = "/login")
    public ModelAndView Login(HttpServletRequest req, Model model){

        ModelAndView mv = new ModelAndView("sys/login");
        String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");

        String error = null;
        if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "当前用户不存在";
        } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "登录密码错误";
        } else if(DisabledAccountException.class.getName().equals(exceptionClassName)) {
            error = "账号被禁用";
        }else if(LockedAccountException.class.getName().equals(exceptionClassName)) {
            error = "账号被锁定";
        }else if(ExcessiveAttemptsException.class.getName().equals(exceptionClassName)) {
            error = "登录失败多次，账户锁定10分钟";
        }else if(ExpiredCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "密码过期";
        }else if(exceptionClassName != null) {
            error = "其他错误：" + exceptionClassName;
        }
        mv.addObject("error", error);

        return mv;
    }
}
